define([
    "UtilDir/util",
    "UtilDir/tool",
    "UtilDir/dialog",
    "UtilDir/org/selectOrg",
    "UtilDir/combotree",
    "UtilDir/searchBlock", "ZTree",
    "EasyUI", "EasyUI-lang", "css!ZTreeCss"
], function (Util, Tool, Dialog, OrgUtil, Combotree, SearchBlock) {

    var sysPath = getServer() + "/static/app/fwsjcj";
    var deptFormHtml = sysPath + "/dept/views/deptForm.html";
    var orgFormHtml = sysPath + "/dept/views/orgForm.html";

    var getDeptController = function () {
        return getServer() + "/platform/org/depts";
    };
    var getOrgConfigController = function () {
        return getServer() + "/platform/org/config";
    };

    var getDivisionController = function () {
        return getServer() + "/platform/org/divisions/";
    };

    var getDictController = function () {
        return getServer() + "/platform/sys/dicts";
    };
    var getRoleController = function () {
        return getServer() + "/platform/org/roles/";
    };


    var currDeptId;
    var currParentId;
    var currDeptName;
    var currDeptCode;
    var deptTreeJson = {};
    var zTreeObj;
    var currNodeId;
    var rootDeptId = "root";

    var tools = [];
    var setting = {
        data: {
            simpleData: {
                enable: true,
                idKey: "deptId",  //节点数据中保存唯一标识的属性名称
                pIdKey: "parentId"    //节点数据中保存其父节点唯一标识的属性名称
            },
            key: {
                name: "deptName"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
            },
            view: {
                dblClickExpand: true
            }

        }, callback: {
            onClick: function (event, treeId, treeNode, clickFlag) {
                currDeptId = treeNode.deptId;
                currNodeId = treeNode.deptId;
                currDeptName = treeNode.deptName;
                currParentId = treeNode.parentId;
                currDeptCode = treeNode.deptCode;
                createDeptGrid();
            },
            onExpand: function (event, treeId, treeNode) {
                //根据ztree的API可以知道， onExpand触发事件会自动带三个参数
                var treeObj = $.fn.zTree.getZTreeObj(treeId);
                var node = treeObj.getNodeByTId(treeNode.tId);
                //没有子节点才去查询
                if (node.children == null || node.children == "undefined") {
                    getDeptTreeChild(node, treeObj);
                }
            }
        }
    };


    // 获取tree的子节点
    var getDeptTreeChild = function (node, treeObj) {
        $.ajax({
            type: 'get',
            dataType: 'json',
            url: getDeptController() + '/' + node.deptId + "/subdepttreenodes",
            success: function (data) {
                if (data.length > 0) {
                    // isParent: 0--false;1--true
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].isParent == 1) {
                            data[i].isParent = true;
                        } else {
                            data[i].isParent = false;
                        }
                    }
                    //添加新节点
                    newNode = treeObj.addNodes(node, data);

                    for (var i = 0; i < data.length; i++) {
                        deptTreeJson[data[i].deptId] = data[i];
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                common.HintMsg('warning', '加载子组织机构树失败，请联系系统维护人员');
            }
        });
    }

    /**
     * 页面初始化
     */
    var init = function () {
        isShowToolbar();
        initSearchBlock();
        queryBtnBind();

    };
    var isShowToolbar = function () {
        $.ajax({
            url: getRoleController() + "/isAdmin",
            type: "get",
            async: false,
            success: function (data) {
                if (data == true) {
                    console.log("isShowButton" + data);
                    tools = [
                        {
                            iconCls: 'fa fa-plus-circle',
                            text: "添加机构",
                            handler: function () {
                                addOrg();
                            }
                        }, {
                            iconCls: 'fa fa-plus-circle',
                            text: "添加部门",
                            handler: function () {
                                addDept();
                            }
                        }, {
                            iconCls: 'fa fa-trash-o',
                            text: "删除",
                            handler: function () {
                                deleteDept();
                            }
                        }, {
                            iconCls: 'fa fa-upload',
                            text: "导入",
                            handler: function () {
                                uploadDept()
                            }
                        }, {
                            iconCls: 'fa fa-download',
                            text: "导出",
                            href: getDeptController() + "/deptExport",
                            handler: function () {
                                var queryDeptCode = $("#deptName").val();
                                var queryDeptName = $("#deptCode").val();
                                var currentExportDeptId;
                                $("#searchForm").attr("action", getServer() + "/platform/org/depts/deptExport");

                                currentExportDeptId = currDeptId;
                                $("#currDeptId").val(currentExportDeptId);

                                $("#searchForm").submit();
                            }
                        }];
                } else {
                    console.log("isShowButton" + data);
                    tools = [
                        {
                            iconCls: 'fa fa-plus-circle',
                            text: "添加机构",
                            handler: function () {
                                addOrg();
                            }
                        }, {
                            iconCls: 'fa fa-plus-circle',
                            text: "添加部门",
                            handler: function () {
                                addDept();
                            }
                        }, {
                            iconCls: 'fa fa-upload',
                            text: "导入",
                            handler: function () {
                                uploadDept()
                            }
                        }, {
                            iconCls: 'fa fa-download',
                            text: "导出",
                            href: getDeptController() + "/deptExport",
                            handler: function () {
                                var queryDeptCode = $("#deptName").val();
                                var queryDeptName = $("#deptCode").val();
                                var currentExportDeptId;
                                $("#searchForm").attr("action", getServer() + "/platform/org/depts/deptExport");

                                currentExportDeptId = currDeptId;
                                $("#currDeptId").val(currentExportDeptId);

                                $("#searchForm").submit();
                            }
                        }];
                }
            }
        });
    };
    var initSearchBlock = function () {
        SearchBlock.init("searchBlock");
    };
    var queryBtnBind = function () {
        $("#btnSearch").click(function () {
            createDeptGrid();
        });
        $("#btnReset").click(function () {
            $("#deptName").val("");
            $("#deptCode").val("");
        });
    };
    var createDeptGrid = function () {
        var queryId = currDeptId;
        var queryName = $("#deptName").val();
        var queryCode = $("#deptCode").val();
        if ((queryName == null || queryName == '') && (queryCode == null || queryCode == '')) {
            queryId = currDeptId;
        } else if (currDeptId == "root") {
            queryId = "";
        }
        $("#deptGrid").datagrid({
            url: getDeptController(),
            method: "GET",
            columns: [[
                {field: "ck", checkbox: true},
                {
                    field: 'deptName', title: '组织机构名称', width: '22%', align: 'left',
                    formatter: function (value, rowData, rowIndex) {
                        if (rowData.deptType == 'dept') {
                            return '<a href="#" onclick="_editDept(\'' + rowData.deptId + '\',\'' + rowData.leaderName + '\',\'' + rowData.leaderCode + '\');"> ' + rowData.deptName + ' </a> '
                        } else if (rowData.deptType == 'org') {
                            return '<a href="#" onclick="_editOrg(\'' + rowData.deptId + '\',\'' + rowData.leaderName + '\',\'' + rowData.leaderCode + '\');"> ' + rowData.deptName + ' </a> '
                        }
                    }
                },
                {field: 'deptCode', title: '组织机构编码', width: '22%', align: 'left'},
                {field: 'leaderName', title: '领导', width: '20%', align: 'left'},
                {field: 'deptTypeName', title: '组织类型', width: '20%', align: 'left'},
                {field: 'sort', title: '顺序号', width: '15%', align: 'center'},
                {field: 'deptType', title: 'deptType', hidden: true}
            ]],
            toolbar: tools,
            queryParams: {
                deptName: queryName,
                deptCode: queryCode,
                currDeptId: queryId
            },
            pagination: true,
            pageSize: 10
        });
    };

    var getDept = function (deptId, deptType) {

        $.ajax({
            url: getDeptController() + "/" + deptId,
            type: "get",
            success: function (data) {
                initDeptLevelSelect(data.deptLevel);

                if (null != data.parentId && "" != data.parentId) {
                    data.parentName = deptTreeJson[data.parentId].deptName;
                    data.parentCode = deptTreeJson[data.parentId].deptCode;
                }
                if (deptType == 'org') {
                    Tool.deserialize("orgForm", data);
                    Tool.deserialize("orgExtendInfoForm", data);
                    initSearchForm('org');
                } else if (deptType == 'dept') {
                    Tool.deserialize("deptForm", data);
                    Tool.deserialize("deptExtendInfoForm", data);
                }

            }
        });
    };

    var addDept = function () {
        var slidebar = Util.slidebar({
            url: deptFormHtml,
            width: "800px",
            cache: false,
            close: true,
            afterLoad: function () {
                deptFormValidator();
                initDeptLevelSelect();
                initSearchForm('dept');
                initDeptExtendInfo("dept");

                $("#parentId").val(currDeptId);
                $("#parentName").val(currDeptName);
                $("#parentCode").val(currDeptCode);

                $("#saveBtn").on("click", function () {

                    if ($("#deptForm").valid()) {

                        var data = {};
                        var deptInfo = Tool.serialize("deptForm");
                        var deptExtendInfo = Tool.serialize("deptExtendInfoForm");
                        data = $.extend({}, deptInfo, deptExtendInfo);

                        data.deptType = "dept";
                        $.ajax({
                            url: getDeptController(),
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "post",
                            success: function (data) {
                                Util.alert("新增部门成功");
                                slidebar.close();
                                initTree();
                            }
                        });
                    }
                });

            }
        });
    };


    var addOrg = function () {
        //deptTreeJson[currDeptId]
        if (deptTreeJson[currDeptId].deptType != 'org') {
            Util.alert('机构需建立在机构下')
            return;
        }

        var slidebar = Util.slidebar({
            url: orgFormHtml,
            width: "800px",
            cache: false,
            close: true,
            afterLoad: function () {
                orgFormValidator();
                initDeptLevelSelect();
                $("#parentId").val(currDeptId);
                $("#parentName").val(currDeptName);
                $("#parentCode").val(currDeptCode);
                $("#saveBtn").on("click", function () {
                    if ($("#orgForm").valid()) {

                        var data = {};
                        var orgInfo = Tool.serialize("orgForm");
                        var orgExtendInfo = Tool.serialize("orgExtendInfoForm");
                        data = $.extend({}, orgInfo, orgExtendInfo);

                        data.deptType = "org";
                        $.ajax({
                            url: getDeptController(),
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "post",
                            success: function (data) {
                                Util.alert('新增机构成功');
                                slidebar.close();
                                initTree();
                            }
                        });
                    }
                });
                initSearchForm('org');
                initDeptExtendInfo("org")
            }
        });
    };

    window._editDept = function (deptId, leaderName, leaderCode) {

        var slidebar = Util.slidebar({
            url: deptFormHtml,
            width: "800px",
            cache: false,
            close: true,
            afterLoad: function () {
                deptFormValidator();
                initDeptLevelSelect();
                getDept(deptId, "dept");
                $("#leaderName").val(leaderName);
                $("#leaderCode").val(leaderCode);
                $("#saveBtn").on("click", function () {
                    if ($("#deptForm").valid()) {
                        var data = {};
                        var deptInfo = Tool.serialize("deptForm");
                        var deptExtendInfo = Tool.serialize("deptExtendInfoForm");
                        data = $.extend({}, deptInfo, deptExtendInfo);
                        $.ajax({
                            url: getDeptController(),
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "put",
                            success: function (data) {
                                Util.alert('修改部门成功');
                                slidebar.close();
                                initTree();
                            }
                        });
                    }
                });
                initSearchForm('dept');
                initDeptExtendInfo("dept")

            }
        });
    };

    window._editOrg = function (deptId, leaderName, leaderCode) {
        var slidebar = Util.slidebar({
            url: orgFormHtml,
            width: "800px",
            cache: false,
            close: true,
            afterLoad: function () {
                orgFormValidator();
                getDept(deptId, "org");
                $("#leaderName").val(leaderName);
                $("#leaderCode").val(leaderCode);
                $("#saveBtn").on("click", function () {
                    if ($("#orgForm").valid()) {
                        var data = {};
                        var orgInfo = Tool.serialize("orgForm");
                        var orgExtendInfo = Tool.serialize("orgExtendInfoForm");
                        data = $.extend({}, orgInfo, orgExtendInfo);
                        $.ajax({
                            url: getDeptController(),
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "put",
                            success: function (data) {
                                Util.alert('修改机构成功');
                                slidebar.close();
                                initTree();
                            }
                        });
                    }
                });
                initDeptExtendInfo("org");

            }
        });
    };

    var deleteDept = function () {

        var rows = $("#deptGrid").datagrid("getSelections");
        if (rows == null || rows.length == 0) {
            Util.alert("请选择一行数据!");
            return;
        }
        Util.confirm("是否要删除选中的组织机构包含的所有数据(包含子部门及机构和子部门下的所有人员)?", function () {
            var ids = "";
            $.each(rows, function (i, row) {
                ids += row.deptId + ",";
            });
            ids = ids.substr(0, ids.length - 1);
            $.ajax({
                url: getDeptController() + '/' + ids,
                type: "patch",
                success: function (data) {
                    Util.alert('删除成功');
                    createDeptGrid();
                    initTree();
                }
            });
        }, function () {
            return;
        });

    };

    function initTree() {
        $.ajax({
            type: "get",
            url: getDeptController() + '/depttreerootnode',
            dataType: "json",
            success: function (data) {
                // isParent: 0--false;1--true
                for (var i = 0; i < data.length; i++) {
                    if (data[i].isParent == 1) {
                        data[i].isParent = true;
                    } else {
                        data[i].isParent = false;
                    }
                }
                // 获取树对象
                var zTreeObj = $.fn.zTree.init($("#deptTreeData"), setting, data);
                // zTreeObj.expandAll(false);
                var zTree = $.fn.zTree.getZTreeObj("deptTreeData");
                var nodeList = zTree.getNodes();

                for (i = nodeList.length - 1; i >= 0; i--) {
                    var rootNode = nodeList[i];
                    if (rootNode != null) {
                        currDeptId = rootNode.deptId;
                        currDeptName = rootNode.deptName;
                        currDeptCode = rootNode.deptCode;
                    }
                    var node = zTreeObj.getNodeByParam("deptId", currNodeId);
                    if (node != null) {
                        zTreeObj.selectNode(node, false);
                    } else {
                        zTreeObj.selectNode(rootNode, false);
                    }

                    if (data[i].isParent) {
                        /* 获取选中树节点 */
                        var nodes = zTreeObj.getSelectedNodes();
                        //展开第一级树
                        zTreeObj.expandNode(nodes[0], true);
                        getDeptTreeChild(nodes[0], zTreeObj);
                    }


                    for (var j = 0; j < data.length; j++) {
                        deptTreeJson[data[j].deptId] = data[j];
                    }

                }
                createDeptGrid();

            }
        });
    }

    //校验
    var deptFormValidator = function () {
        $("#deptForm").validate({
            ignore: "hidden",
            ignore: "",
            rules: {
                deptName: {
                    required: true,
                    maxlength: 100
                },
                deptCode: {
                    required: true,
                    maxlength: 32,
                    remote: {
                        type: "GET",
                        url: getDeptController() + "/validateDeptCode",
                        data: {  //要传递的参数
                            deptId: function () {
                                return $("#deptForm #deptId").val();
                            },
                            deptCode: function () {
                                return $("#deptForm #deptCode").val();
                            }
                        }
                    }
                },
                sort: {
                    digits: true,
                    min: 1,
                    max: 255
                }
            },
            messages: {
                deptName: {
                    required: "部门名称不允许为空!",
                    maxlength: "部门名称长度不可以超过100"
                },
                deptCode: {
                    required: "部门编码不允许为空!",
                    maxlength: "部门编码长度不可以超过30",
                    remote: "部门编码不能重复"
                },
                sort: "顺序号必须是小于256的正整数"
            }
        });
    };

    //导入
    function uploadDept() {
        $("#uploadModal").modal();
        $("#uploadModal").on("shown.bs.modal", function () {
            var url = getDeptController() + "/deptTemplate";
            $("#deptTemplate").attr("href", url);
        });

        $('#uploadButton').off("click");
        $("#uploadButton").on("click", function () {
            var uploadinput = document.getElementById("uploadFile");
            if (uploadinput.value == "") {
                Util.alert("上传前请先选择文件!");
                return;
            }
            var formData = new FormData();
            formData.append("file", uploadinput.files[0]);
            $.ajax({
                url: getDeptController() + "/deptExcel",
                data: formData,
                processData: false, //因为data值是FormData对象，不需要对数据做处理。
                contentType: false,
                type: "POST",
                success: function (data) {
                    $('#uploadModal').modal('hide');
                    uploadinput.value = null;
                    Util.alert(data);
                    createDeptGrid();
                    initTree();
                }
            });
        });
    };

    var initDeptLevelSelect = function (deptLevel) {
        $('#deptLevelSelect').empty();
        $.ajax({
            url: getDictController() + "/getValidDictItemsByDictCode/deptLevel",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("deptLevelSelect");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }

                if (deptLevel != null && deptLevel != '') {
                    mySelect.value = deptLevel;
                }

                $('#deptLevelSelect').on('change', function () {

                    $('#deptLevel').val($('#deptLevelSelect').val());

                });

            }
        });

    };

    //校验
    var orgFormValidator = function () {
        $("#orgForm").validate({
            ignore: "hidden",
            ignore: "",
            rules: {
                deptName: {
                    required: true,
                    maxlength: 100
                },
                deptCode: {
                    required: true,
                    maxlength: 32,
                    remote: {
                        type: "GET",
                        url: getDeptController() + "/validateDeptCode",
                        data: {  //要传递的参数
                            deptId: function () {
                                return $("#orgForm #deptId").val();
                            },
                            deptCode: function () {
                                return $("#orgForm #deptCode").val();
                            }
                        }
                    }
                },
                sort: {
                    digits: true,
                    min: 1,
                    max: 255
                },
                zipCode: {
                    zipCode: true,
                    maxlength: 6,
                },
                telephone: {
                    officePhone: true,
                    maxlength: 17
                },
                divisionName: {
                    required: true
                }
            },
            messages: {
                deptName: {
                    required: "机构名称不允许为空!",
                    maxlength: "机构名称长度不可以超过100"
                },
                deptCode: {
                    required: "机构编码不允许为空!",
                    maxlength: "机构编码长度不可以超过30",
                    remote: "机构编码不能重复"
                },
                sort: "顺序号必须是小于256的正整数",
                zipCode: {
                    zipCode: "请输入正确格式的邮编",
                    maxlength: "邮编编码长度必须为6位"

                },
                telephone: {
                    officePhone: "请输入正确格式的办公电话号",
                    maxlength: "办公电话号长度不可以超过17"
                },
                divisionName: {
                    required: "行政区划不允许为空!"
                }
            }
        });
    };

    /**
     * 初始化选人面板,下拉机构树，下来行政区划树
     */
    var initSearchForm = function (deptType) {


        var getTreePath;

        if (deptType == 'dept') {
            getTreePath = '/getDeptTree'
        } else if (deptType = 'org') {
            getTreePath = '/getOrgTree'
        }

        OrgUtil.init({
            id: "leaderName",
            multi: false,
            title: "请选择人员",
            hideTag: true,
            tagType: ["user"],
            callback: function (data) {
                $("#leaderId").val(data.user[0].userId);
                $("#leaderName").val(data.user[0].userName);
                $("#leaderCode").val(data.user[0].userCode);
            }
        });


        //初始化
        var combotree = Combotree({
            // combo组件相关配置
            combo: {
                //要渲染的input的id
                id: "parentName",
                //下拉框的类型：单选or多选
                multi: false,
                key: {
                    idKey: "deptId",
                    textKey: "deptName"
                },
//          placeholder: "请选择……",
                event: {
                    onShowPanel: function () {
                    },
                    onHidePanel: function () {
                    },
                    onChange: function (newData, oldData) {

                        if ($("#parentId").parent().attr("id") == 'orgForm') {
                            if (newData[0].deptType != 'org') {
                                $("#parentId").val("");
                                $("#parentName").val("");
                                $("#parentCode").val("");
                                Util.alert('机构需建在机构下！');
                            }
                        }
                        if (null != newData && newData.length > 0) {
                            $("#parentId").val(newData[0].deptId);
                            $("#parentCode").val(newData[0].deptCode);
                            $("#parentName").val(newData[0].deptName);

                        }
                    }
                }
            },
            // ztree组件相关配置
            ztree: {
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "deptId", // 主键属性名
                        pIdKey: "parentId" // 父节点属性名
                    },
                    key: {
                        name: "deptName" // 显示名称属性名
                    }
                },
                check: {
                    chkboxType: {
                        'Y': '',
                        'N': ''
                    }
                }
            },
            data: {
                url: getDeptController() + getTreePath,
                type: "GET",
                success: function () {

                }
            },
            formatter: function (node) {
                //if (node.id == "0") {
                node.open = true;
                //}
            },
            search: {
                enable: true,
                fields: ["deptName"]
            }
        });


        //初始化行政岗区划
        var combotree = Combotree({
            // combo组件相关配置
            combo: {
                //要渲染的input的id
                id: "divisionName",
                //下拉框的类型：单选or多选
                multi: false,
                key: {
                    idKey: "divisionId",
                    textKey: "divisionName"
                },
                //          placeholder: "请选择……",
                event: {
                    onShowPanel: function () {
                        console.log("show");
                    },
                    onHidePanel: function () {
                        console.log("hide");
                    },
                    onChange: function (n, o) {
                        $("#divisionId").val(n[0].divisionId);
                        $("#divisionName").val(n[0].divisionName);
                    }
                }
            },
            // ztree组件相关配置
            ztree: {
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "divisionId", // 主键属性名
                        pIdKey: "parentId" // 父节点属性名
                    },
                    key: {
                        name: "divisionName" // 显示名称属性名
                    }
                },
                check: {
                    chkboxType: {
                        'Y': '',
                        'N': ''
                    }
                }
            },
            data: {
                url: getDivisionController() + 'initDivisionZtree',
                type: 'GET',
                success: function () {

                }
            },
            formatter: function (node) {
                node.open = true;
            },
            value: $("#divisionId").val(),
            search: {
                enable: true,
                fields: ["divisionName"]
            }
        });

    };


    var initDeptExtendInfo = function (deptType) {
        $.ajax({
            url: getOrgConfigController(),
            type: "get",
            success: function (data) {
                if (null != data) {
                    var deptExtendConfigData;
                    if (deptType == 'org') {
                        deptExtendConfigData = JSON.parse(data.orgExtendConfig);
                    } else if (deptType == 'dept') {
                        deptExtendConfigData = JSON.parse(data.deptExtendConfig);
                    }
                    for (var i = 1; i < 11; i++) {
                        if (deptExtendConfigData != null) {
                            if (deptExtendConfigData['extend' + i] != null && "" != deptExtendConfigData['extend' + i]) {
                                $("#extend" + i).parent().prev().text(deptExtendConfigData['extend' + i] + ":")
                            }
                        }
                    }
                }

            }
        });

    };

    $("#highManage").on('shown.bs.tab', function () {
        initSearchUserBlock();
        queryDeptBtnBind();
        createDeleteDeptTree();
        createDeleteDeptGrid();
        initDeptTree();
    });


    function initDeptTree() {
        var treeObj = $.fn.zTree.getZTreeObj("deptTree");
        treeObj.selectNode(treeObj.getNodes()[0], false);
    }


    function initSearchUserBlock() {
        SearchBlock.init("searchDeptBlock");
    }

    var queryDeptBtnBind = function () {
        $("#searchBtn").click(function () {
            createDeleteDeptGrid();
        });
        $("#resetBtn").click(function () {
            $("#deleteDeptName").val("");
            $("#deleteDeptCode").val("");
        });
    };
    var createDeleteDeptTree = function () {
        var zNodes = [
            {name: "已删除部门", "id": 1}
        ];
        var setting = {
            simpleData: {
                idKey: "id"
            },
            callback: {
                onClick: function (event, treeId, treeNode, clickFlag) {
                    if (treeNode.id == 1) {
                        createDeleteDeptGrid();
                        param = 1;
                    } else {
                        //若添加节点，在此添加。
                    }
                }
            }
        };
        $.fn.zTree.init($("#deptTree"), setting, zNodes);

    }

    var createDeleteDeptGrid = function () {
        var queryName = $("#deleteDeptName").val();
        var queryCode = $("#deleteDeptCode").val();


        $("#deleteGrid").datagrid({
            url: getDeptController() + "/deleteddepts",
            method: "GET",
            columns: [[
                {field: "ck", checkbox: true},
                {field: 'deptName', title: '部门名称', width: '49%'},
                {field: 'deptCode', title: '部门编码', width: '49%'}
            ]],
            toolbar: [{
                iconCls: 'fa fa-reply',
                text: "恢复",
                handler: function () {
                    revertDepts();
                }
            }],
            queryParams: {
                deptName: queryName,
                deptCode: queryCode,
            },
            pagination: true,
            pageSize: 10
        });
    };

    var revertDepts = function () {
        var rows = $("#deleteGrid").datagrid("getSelections");
        if (rows == null || rows.length == 0) {
            Util.alert("请选择一行数据!");
            return;
        }
        Util.confirm("是否恢复选中部门", function () {
            var ids = "";
            $.each(rows, function (i, row) {
                ids += row.deptId + ",";
            });
            ids = ids.substr(0, ids.length - 1);
            $.ajax({
                url: getDeptController() + '/revertdepts',
                data: {
                    ids: ids
                },
                type: "patch",
                success: function (data) {
                    Util.alert("恢复用户信息成功!");
                    createDeleteDeptGrid();
                }
            });
        }, function () {
            return;
        });
    }


    /**
     * 初始化zTree
     */
    $(document).ready(function () {

        initTree();
    });

    return {
        init: init
    };
});
